package com.zxkj.commonpatrol.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.czy.basecommon.utils.base.BaseVmDataBindingActivity;
import com.czy.basecommon.utils.base.StateData;
import com.czy.basecommon.utils.tools.ActivityTool;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener;
import com.xuexiang.xui.widget.toast.XToast;
import com.zxkj.commonpatrol.BR;
import com.zxkj.commonpatrol.R;
import com.zxkj.commonpatrol.adapt.QuestEventListAdapt;
import com.zxkj.commonpatrol.adapt.QuestListAdapt;
import com.zxkj.commonpatrol.databinding.ActivityAddEventBinding;
import com.zxkj.commonpatrol.model.response.PointInspectEvent;
import com.zxkj.commonpatrol.model.response.Questions;
import com.zxkj.commonpatrol.viewmodel.AddEventViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddEventActivity extends BaseVmDataBindingActivity<ActivityAddEventBinding, AddEventViewModel> {
    //查看和编辑 复用
    private  int type=0;//0  查看,1 編輯
    private QuestEventListAdapt adapt;
    private String RouteInspectNo;
    private String PointNo;
    private String EventNo;
    private String RSName;
    private OptionsPickerView<Object> mQuestType;
    private int mQuestTypeOption;
    private HashMap<String, List<Questions.QuestionItem>> hashMapQuestTypeDatas;
    private HashMap<String, String> hashMapQuestTypeDatas1;
    private String QuestsNo;
    private MiniLoadingDialog loadingDialog;
    public int IsAdd=0;//是否新增（1：新增  0：编辑 查看）
    public String EventCode="";
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_add_event;
    }

    @Override
    public int initVariableId() {
        return BR.AddEventViewModel;
    }



    @Override
    protected void initUI() {
        if (getIntent().hasExtra("IsEdit")){
            type=getIntent().getIntExtra("IsEdit",0);
        }
        if (getIntent().hasExtra("RouteInspectNo")){
            RouteInspectNo=getIntent().getStringExtra("RouteInspectNo");
        }
        if (getIntent().hasExtra("PointNo")){
            PointNo=getIntent().getStringExtra("PointNo");
        }
        if (getIntent().hasExtra("EventNo")){
            EventNo=getIntent().getStringExtra("EventNo");
        }
        if (getIntent().hasExtra("RSName")) {
            RSName = getIntent().getStringExtra("RSName");
        }

        viewModel.RSName.set(RSName);
        EditText a[]={binding.edPointQuestList};
        EditText b[]={binding.edPointEnName,binding.edPointCnLocation};
        if (type==0){
            //查看
            IsAdd=0;
            binding.tvTitle.setText("查看事件");
            binding.btnNo.setVisibility(View.VISIBLE);
            setCheckFalse(a);
        }else{
            IsAdd=1;
            binding.btnNo.setVisibility(View.VISIBLE);
            //編輯
            binding.tvTitle.setText("新增事件");
            setCheckTrue(b);

        }

        binding.recyList.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void initData() {
        if (type==0) {
            //查看

            viewModel.getEventDetail(RouteInspectNo,PointNo,EventNo);
        }else{
            //编辑
            viewModel.getEventList(RouteInspectNo,PointNo);
        }


    }
    public void  setCheckFalse(EditText...editTexts){
        for (EditText editText: editTexts) {
            editText.setFocusable(false);
            editText.setEnabled(false);
            editText.setFocusableInTouchMode(false);
        }
    }
    public void  setCheckTrue(EditText...editTexts){
        for (EditText editText: editTexts) {
            editText.setFocusable(true);
            editText.setEnabled(true);
            editText.setFocusableInTouchMode(true);
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        binding.edPointQuestList.setOnClickListener(v->{
            if (mQuestType!=null){
                mQuestType.show();
            }
        });
        binding.btnNo.setOnClickListener(v->{
            if (loadingDialog == null) {
                loadingDialog = new MiniLoadingDialog(this, "加載中...");
            }
            loadingDialog.show();
            viewModel.Save(QuestsNo,PointNo,RouteInspectNo,EventCode,IsAdd);
        });
        binding.qkBack.setOnClickListener(v->{
            ActivityTool.getInstance().popOneActivity(this);
        });
    }

    @Override
    protected void dataObserver() {
        super.dataObserver();
           viewModel.QuestListData.observe(this, new Observer<StateData<List<PointInspectEvent.QuestionItem>>>() {
               @Override
               public void onChanged(StateData<List<PointInspectEvent.QuestionItem>> listStateData) {
                   List<String> datas=new ArrayList<>();
                   for (int i = 0; i < listStateData.getData().size(); i++) {
                       datas.add(listStateData.getData().get(i).Name);
                   }

                   if (adapt==null){
                    adapt =new QuestEventListAdapt(R.layout.item_quest_list,datas);
                    binding.recyList.setAdapter(adapt);
                }else{
                    adapt.setNewData(datas);
                }
               }
           });
           viewModel.EventCode.observe(this, new Observer<StateData<String>>() {
               @Override
               public void onChanged(StateData<String> stringStateData) {
                   if (stringStateData.getStatus()== StateData.DataStatus.SUCCESS){
                       EventCode=stringStateData.getData();
                   }
               }
           });
           viewModel.QuestsNo.observe(this, new Observer<StateData<String>>() {
               @Override
               public void onChanged(StateData<String> stringStateData) {
                   QuestsNo=stringStateData.getData();
               }
           });
           viewModel.QuestEventList.observe(this, new Observer<StateData<List<Questions>>>() {
               @Override
               public void onChanged(StateData<List<Questions>> listStateData) {



                   ArrayList<String> list = new ArrayList();
                   hashMapQuestTypeDatas = new HashMap<>();
                   hashMapQuestTypeDatas1 = new HashMap<>();
                   for (int i = 0; i < listStateData.getData().size(); i++) {
                       list.add(listStateData.getData().get(i).QuestsName);
                       hashMapQuestTypeDatas1.put(listStateData.getData().get(i).getQuestsName(),listStateData.getData().get(i).getQuestsCode());
                       hashMapQuestTypeDatas.put(listStateData.getData().get(i).getQuestsName(),listStateData.getData().get(i).getQuesItems());
                   }
                   int size4 = list.size();
                   String[] array4 = (String[]) list.toArray(new String[size4]);
                   QuestType(array4);
               }
           });
//        viewModel.datas.observe(this, new Observer<StateData<List<String>>>() {
//            @Override
//            public void onChanged(StateData<List<String>> listStateData) {
//                if (adapt==null){
//                    adapt =new QuestListAdapt(R.layout.item_quest_list,listStateData.getData());
//                    binding.recyList.setAdapter(adapt);
//                }else{
//                    adapt.setNewData(listStateData.getData());
//                }
//            }
//        });
        viewModel.save.observe(this, new Observer<StateData<Object>>() {
            @Override
            public void onChanged(StateData<Object> objectStateData) {
                if (loadingDialog!=null){
                    loadingDialog.dismiss();
                }
                if (objectStateData.getStatus()== StateData.DataStatus.SUCCESS){
                    XToast.success(AddEventActivity.this,"保存成功").show();

                    ActivityTool.getInstance().popOneActivity(AddEventActivity.this);
                }else{
                    XToast.error(AddEventActivity.this,"保存失敗").show();
                }
            }
        });
    }
    private void QuestType(final String[] o) {
        mQuestType = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public boolean onOptionsSelect(View view, int options1, int options2, int options3) {
                binding.edPointQuestList.setText(o[options1]);
                mQuestTypeOption = options1;
                //設置問題集數據
                setQuestListData(o[options1]);
                QuestsNo=hashMapQuestTypeDatas1.get(o[options1]);
//                CategoryCode=hashMap.get(o[options1]);
                return false;
            }


        }).setCancelText("取消")//取消按钮文字
                .setSubmitText("確認")//确认按钮文字
                .setTitleText("請選擇問題集")
                .setSubCalSize(16)
                .setSubCalSize(16)

                .setSelectOptions(mQuestTypeOption)
                .build();
        mQuestType.setPicker(o);

    }

    private void setQuestListData(String s) {
        List<Questions.QuestionItem> questionItems = hashMapQuestTypeDatas.get(s);
        List<String> datas=new ArrayList<>();
        for (int i = 0; i < questionItems.size(); i++) {
            datas.add(questionItems.get(i).Name);
        }

        if (adapt==null){
            adapt =new QuestEventListAdapt(R.layout.item_quest_list,datas);
            binding.recyList.setAdapter(adapt);
        }else{
            adapt.setNewData(datas);
        }
    }
}
